<?php


namespace api\modules\v1\controllers\common;

use common\models\clinic\Project;
use common\models\member\Member;
use common\models\rbac\Role;
use common\queues\ExportJob;
use services\common\CommonService;
use services\export\LogService;
use services\patient\UserService;
use Yii;
use services\baibai\ConfigService;
use api\controllers\OnAuthController;
use yii\web\HttpException;

class ExportController extends OnAuthController
{
    public $modelClass = '';

    protected $optional = ['test'];
    /**
     * 获取筛选条件的字段列表
     * $params['choose_id']
     * 1:性别，2:医助归属人，3:客服归属人，4:诊室，5:就诊类型，6:患者标签，7:地区，8:来源，9:病种，10:治疗项目，11:操作人
     * @return array
     * @throws HttpException
     * @author chenyuebin
     */

    public function actionExportExcel()
    {
        $params = Yii::$app->request->post();

        $field = explode(',' ,$params['field']);
        /*$service = new UserService();
        return $service->getPatientUserCardId(
            $params, $field, 1, 1, $this->projectId
        );*/
        $logService = new LogService();
        // 文件名称和存储路径
        $nameAndPath = $logService->nameAndPAth(ConfigService::GENERAL_ID, Yii::$app->user->identity->member->realname, $this->projectId);

        // 创建导出日志并获取日志id
        $logId = Yii::$app->services->exportLog->createLog([
            'project_id' => $this->projectId,
            'mudle_name' => $nameAndPath['preName'],
            'handle' => Yii::$app->user->identity->member->realname,
            'project_short_name' => $nameAndPath['project_sx']
        ]);

        if (!$logId) {
            throw new HttpException(422, '导出日志创建失败！');
        }

        // 队列开始
        $id = Yii::$app->queue->push(new ExportJob([
            'logId' => $logId,
            'nameAndPath' => $nameAndPath,
            'select' => $params,
            'project_id' => $this->projectId,
            'mudle_id' => 1,
            'condition' => $field,
            'handle' => Yii::$app->user->identity->member->realname
        ]));

        return $id;
    }

    public function actionSelectInfo()
    {

        $field_list = ConfigService::MUDEL_LIST_FIELD[ConfigService::GENERAL_ID];
        //处理 字段合并, 基本信息(姓名,性别,年龄), 上次回访时间(客服上次回访,医助上次回访)
        $base = [
            'id' => ConfigService::NAME_ID . ',' . ConfigService::GENDER_ID . ',' . ConfigService::AGE_ID,
            'name' => '基本信息'
        ];
        // 上次回访时间
        $last_callback = [
            'id' => ConfigService::KF_LAST_CALLBACK_ID . ',' . ConfigService::YZ_LAST_CALLBACK_ID ,
            'name' => '上次回访时间'
        ];


        foreach ($field_list as $key => &$item) {

            $item['id'] = (string)$item['id'];
            // 合并基本信息
            if ($item['id'] == ConfigService::NAME_ID || $item['id'] == ConfigService::GENDER_ID || $item['id'] == ConfigService::AGE_ID) {
                unset($field_list[$key]);
            }
            // 合并回访时间
            if ($item['id'] == ConfigService::KF_LAST_CALLBACK_ID || $item['id'] == ConfigService::YZ_LAST_CALLBACK_ID ) {
                unset($field_list[$key]);
            }

            // 合并病种
            if ($item['id'] == ConfigService::PATIENT_DISEASES_ID ) {
                $item['id'] .= ','. ConfigService::PATIENT_CHILD_DISEASES_ID;
            }
            if ($item['id'] == ConfigService::PATIENT_CHILD_DISEASES_ID) {
                unset($field_list[$key]);
            }
        }

        array_unshift ($field_list ,$base);

        $condition = Yii::$app->services->patientUser->getConditionList([
            'get_medical_member' => 1,
            'get_customer_member' => 1,
            'get_clinic' => 1,
        ], $this->projectId);
        $condition['outpatient_type_list'] = CommonService::getOutpatientTypeList(0);
        $condition['patient_diseases_list'] = CommonService::getDiseasesList();

        return [
            'field_list' => $field_list,
            'info' => $condition,
        ];
    }


    public function actionShowSelect()
    {
        $params = Yii::$app->request->get();
        if (!isset($params['choose_id']) || !$params['choose_id']) {
            throw new HttpException(422, '请选择要获取的数据');
        }
        if (!in_array($params['choose_id'], [
            ConfigService::GENDER_ID,
            ConfigService::BELONG_ASSISTANT_ID,
            ConfigService::BELONG_MEMBER_ID,
            ConfigService::CLINIC_ID,
            ConfigService::OUTPATIENT_TYPE_ID,
            ConfigService::TAGS_ID,
            ConfigService::CITY_NAME_ID,
            ConfigService::SOURCE_CHANNEL_ID,
            ConfigService::PATIENT_DISEASES_ID,
            ConfigService::CLINIC_PROJECT_NAME_ID,
            ConfigService::OPERATE_NAME_ID,
            ConfigService::YZ_LAST_CALLBACK_USER_ID,
            ConfigService::KF_LAST_CALLBACK_USER_ID
        ])) {
            return [];
        }

        $condition = [];
        switch ($params['choose_id']) {
            case ConfigService::GENDER_ID:// 性别
                $condition['get_gender'] = 1;
                break;
            case ConfigService::BELONG_ASSISTANT_ID:// 医助归属人
                $condition['get_medical_member'] = 1;
                break;
            case ConfigService::BELONG_MEMBER_ID:// 客服归属人
                $condition['get_customer_member'] = 1;
                break;
            case ConfigService::YZ_LAST_CALLBACK_USER_ID:// 上次回访人医助
                $condition['get_medical_member'] = 1;
                break;
            case ConfigService::KF_LAST_CALLBACK_USER_ID:// 上次回访人客服
                $condition['get_customer_member'] = 1;
                break;
            case ConfigService::CLINIC_ID:// 诊室
                $condition['get_clinic'] = 1;
                break;
            case ConfigService::CITY_NAME_ID:// 地区
                $condition['get_city'] = 1;
                break;
            case ConfigService::SOURCE_CHANNEL_ID:// 来源
                $condition['get_source_channel'] = 1;
                break;
            default:
                break;
        }

        if ($params['choose_id'] == ConfigService::CLINIC_PROJECT_NAME_ID) {// 治疗项目列表
            $data = Yii::$app->services->clinicProject->findList([
                'select' => ['id', 'name', 'status'],
                'project_id' => $this->projectId,
                'status' => Project::STATUS_ENABLE
            ]);

            return Yii::$app->services->clinicProject->findListFormat($data);

        } else if ($params['choose_id'] == ConfigService::OPERATE_NAME_ID) {// 操作人（护士列表）
            // 获取角色为护士的人员id列表
            $roleMember = Yii::$app->services->userRole->findList([
                'select' => ['member_id'],
                'project_id' => $this->projectId,
                'role_id' => Role::ID_NURSE
            ]);
            $memberIdList = Yii::$app->services->userRole->getMemberList($roleMember);

            // 获取护士id和姓名列表
            $memberList = Yii::$app->services->member->findList([
                'select' => ['id', 'realname'],
                'id' => $memberIdList,
                'status' => Member::STATUS_ENABLE
            ]);

            return Yii::$app->services->member->findListFormat($memberList);
        } else if ($params['choose_id'] == ConfigService::OUTPATIENT_TYPE_ID) {// 就诊类型
            return CommonService::getOutpatientTypeList(0);
        } else if ($params['choose_id'] == ConfigService::TAGS_ID) {// 标签
            return CommonService::getTagsList();
        } else if ($params['choose_id'] == ConfigService::PATIENT_DISEASES_ID) {// 病种【一级】
            return CommonService::getDiseasesList();
        }

        $ret = Yii::$app->services->patientUser->getConditionList($condition, $this->projectId);

        $row = [];
        foreach ($ret as $value) {
            $row['data'] = $value;
        }

        return $row['data'];
    }

    /**
     * 获取模块列表以及导出的字段列表
     * @return array
     * @throws HttpException
     * @author chenyuebin
     */
    public function actionMudleInfo()
    {
        $params = Yii::$app->request->get();
        if (!isset($params['mudle_id']) || !$params['mudle_id']) {
            throw new HttpException(422, '请选择模块');
        }

        return [
            'mudle_list' => ConfigService::MUDLE_LIST,
            'field_list' => ConfigService::MUDEL_LIST_FIELD[$params['mudle_id']],
            'select_field_list' => ConfigService::FIELD_SELECT[$params['mudle_id']],
        ];
    }

    /**
     * 数据导出
     *
     * @return string|null
     * @throws HttpException
     * @author chenyuebin
     */
//    public function actionRunExport()
//    {
//        $params = Yii::$app->request->post();
//        if (!isset($params['mudle_id']) || !$params['mudle_id']) {
//            throw new HttpException(422, '请选择要导出的模块');
//        }
//        if (!isset($params['select']) || !$params['select']) {
//            throw new HttpException(422, '请选择要导出的内容');
//        }
//
//        $conditions = isset($params['condition']) && $params['condition'] ? json_decode($params['condition'], true) : [];
//
//        $logService = new LogService();
//        // 文件名称和存储路径
//        $nameAndPath = $logService->nameAndPAth($params['mudle_id'], Yii::$app->user->identity->member->realname, $this->projectId);
//        //$savePath = \Yii::getAlias('@attachment') . '/' . $fileName;
//
//        // 创建导出日志并获取日志id
//        $logId = Yii::$app->services->exportLog->createLog([
//            'project_id' => $this->projectId,
//            'mudle_name' => $nameAndPath['preName'],
//            'handle' => Yii::$app->user->identity->member->realname,
//            'project_short_name' => $nameAndPath['project_sx']
//        ]);
//
//        if (!$logId) {
//            throw new HttpException(422, '导出日志创建失败！');
//        }
//
////         return Yii::$app->services->patientUser->getPatientList($logId, $nameAndPath, json_decode($params['select'], true), $this->projectId, $params['mudle_id'], $conditions);
//        // 队列开始
//        $id = Yii::$app->queue->push(new ExportJob([
//            'logId' => $logId,
//            'nameAndPath' => $nameAndPath,
//            'select' => json_decode($params['select'], true),
//            'project_id' => $this->projectId,
//            'mudle_id' => $params['mudle_id'],
//            'condition' => $conditions,
//            'handle' => Yii::$app->user->identity->member->realname
//        ]));
//
//        return $id;
//        //以下为获取该队列状态：
//        //这个作业等待执行。
//        //Yii::$app->queue->isWaiting($id);
//
//        // Worker从队列获取作业，并执行它。
//        //Yii::$app->queue->isReserved($id);
//
//        // Worker作业执行完成。
//        //Yii::$app->queue->isDone($id);
//    }

    /**
     * 导出日志
     *
     * @return array
     * @author chenyuebin
     */
    public function actionExportLog()
    {
        $params = Yii::$app->request->get();

        return Yii::$app->services->exportLog->exportLog($this->projectId, $params['page'], $params['pageSize']);
    }
}
